package newpackage;

import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
// Lab session: here is a list of things to be fixed in this client:
// 1. catch command line error (missing  or wrong arguments) and exit with an error message
// 2. write a cleanUp method that close streams and sockets no matter what! put calls to this methid in the rigt place
// 3. add a loop so that the client sends 10 times the requests to the server, put a sleep(1000) between each call.

// A client of an HelloServer
class HelloClient {

    public static void main(String[] args) 
    {
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        
        Socket connection = null;
        try {
            connection = new Socket(hostname, port);
        } catch (IOException ioe) {
            System.err.println("Connection failed");                    
            return;
        }
            try {
            BufferedReader reader = 
                            new BufferedReader(new InputStreamReader (connection.getInputStream ()));
            PrintWriter writer = 
                            new PrintWriter   (new OutputStreamWriter(connection.getOutputStream()));

            writer.println(args[2]); // client name
            writer.flush();
            String reply = null;
            //reply = reader.readLine();
            //System.out.println("Server reply: "+reply);    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
            writer.println("1");
            writer.flush();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
            reply = reader.readLine();
            System.out.println("Server reply: "+reply); 
            
            writer.println("2");
            writer.flush();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
            reply = reader.readLine();
            System.out.println("Server reply: "+reply); 
            
            
            reader.close();
            writer.close();
    	} 
        catch (IOException ioe1) {}
    	finally 
        {
            try 
            { 
                connection.close();
            }
            catch (IOException ioe) {}
    	} 
    }
}

